package com.cmsz.cashier.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.ModelAndView;

import com.cmsz.cashier.bean.CashierOrderInoBean;
import com.cmsz.cashier.mapper.WxAppIdSecretMapper;
import com.cmsz.cashier.utils.CommonConstants;
import com.cmsz.framework.http.HttpClient;
import com.cmsz.framework.log.LogHandler;
import com.cmsz.framework.util.JsonUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping("/cashier")
public class WxOpenIdController {
	
	private static LogHandler logger = LogHandler.getLogger(WxOpenIdController.class);
	@Value("${weixin.openid.url}")
	private String wxOauthUrlForOpenid;  
	@Autowired
	private HttpClient httpClient;
	@Autowired
	WxAppIdSecretMapper wxAppIdSecretMapper;
	@ResponseBody
	@RequestMapping(value = "/getopenid",produces = "text/html; charset=utf-8", method = { RequestMethod.POST,
			RequestMethod.GET })
	public ModelAndView getcode(HttpServletRequest req,HttpServletResponse rsp) throws IOException {
		ModelAndView modelAndView = new ModelAndView();
		CashierOrderInoBean orderBean = null;
		try {
			String code = req.getParameter("code");
			String state  = req.getParameter("state");
			String orderjsonBase64 = req.getParameter("orderdata");
			String orderjson = new String(java.util.Base64.getDecoder().decode(orderjsonBase64));
			orderBean = JsonUtil.jsonStr2Obj(orderjson, CashierOrderInoBean.class);
			logger.info("收银台|WxOpenIdController|接收到微信响应code",orderBean);
			logger.messageReceive("收银台|WxOpenIdController|接收到微信响应code："+code+",state:"+state+",orderjson:"+orderjson);
			if(StringUtils.isBlank(code)){
				throw new RuntimeException("获取code为空");
			}
			String openId = getOpenIdFormWx(code,orderBean);
			logger.info("收银台|WxOpenIdController|接收到openID：" + openId,null);
			logger.messageReceive("收银台|WxOpenIdController|接收到openID：" + openId);
			if (StringUtils.isBlank(openId)) {
				throw new RuntimeException("获取openid为空");
			}
			orderBean.setWeixinOpenId(openId);
			orderBean.setPaymentType("WEIXIN-JSAPI");
			
			modelAndView.addObject("orderBean", orderBean);
			modelAndView.setViewName(CommonConstants.PAY_PAGE);
			logger.info("收银台|WxOpenIdController|设置页面参数完成",orderBean);
			logger.messageSend("收银台|WxOpenIdController|设置页面参数完成："+orderBean.toString());
			return modelAndView;
		} catch (Exception e) {
			logger.error("收银台|WxOpenIdController|获取openid失败",e);
			modelAndView.addObject("orderBean", orderBean);
			logger.error("收银台|WxOpenIdController|订单提交失败",e);
			modelAndView.setViewName(CommonConstants.ERROR_PAGE);
			return modelAndView;
		}
//	return deferredResult;
	}

	
	
	private String getOpenIdFormWx(String code, CashierOrderInoBean orderBean) {
//		https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
		String openId = "";
		try {
			String tokenUrl = wxOauthUrlForOpenid;
			String wxsecret = wxAppIdSecretMapper.selectSecretByAppId(orderBean.getWeixinAppId());
			if(StringUtils.isBlank(wxsecret)){
				throw new RuntimeException("无法找到APPID:"+orderBean.getWeixinAppId()+"对应的secret");
			}
			String data = "appid="+orderBean.getWeixinAppId()+"&secret="+wxsecret+"&code="
					+code+"&grant_type=authorization_code";
			logger.info("收银台|WxOpenIdController|向微信请求获取token完成",orderBean);
			logger.messageSend("收银台|WxOpenIdController|向微信请求获取token：" + data);
			String rspJson = httpClient.sendStringMsg(tokenUrl, data);
			logger.info("收银台|WxOpenIdController|接收到微信token响应完成",orderBean);
			logger.messageReceive("收银台|WxOpenIdController|接收到微信token响应："+rspJson);
			ObjectMapper mapper = new ObjectMapper();
			JsonNode node= mapper.readTree(rspJson); 
			/**
			 * {
				   "access_token":"ACCESS_TOKEN",
				   "expires_in":7200,
				   "refresh_token":"REFRESH_TOKEN",
				   "openid":"OPENID",
				   "scope":"SCOPE",
				   "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
				}   
			 */
			openId = node.get("openid").toString();
			openId = openId.substring(openId.indexOf("\"")+1,openId.lastIndexOf("\""));
		} catch (Exception e) {
			throw new RuntimeException("获取微信用户openID失败"+e.getMessage(),e);
		}
		return openId;
	}
}
